from flask import Flask, jsonify, request
import uuid
import json

app = Flask(__name__)

# 加载 JSON 数据库文件
def load_database(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

# 模拟危机处理响应数据
crisis_responses = load_database('./DBFiles/crisis_responses_db.json')

@app.route('/detect_crisis', methods=['POST'])
def detect_crisis():
    # data = request.get_json()
    # user_message = data.get('user_message')
    user_message = "我很绝望！！！"

    # 简单模拟危机检测，实际需更复杂的语义分析
    if "不想活了" in user_message:
        return jsonify({"is_crisis": True, "crisis_level": "您目前的心理危机状态为重度，请为您转接危机服务"})
    elif "很绝望" in user_message:
        return jsonify({"is_crisis": True, "crisis_level": "您目前的心理危机状态为中度，请为您转接危机服务"})
    elif "有点沮丧" in user_message:
        return jsonify({"is_crisis": True, "crisis_level": "您目前的心理危机状态为轻度，请您注意"})
    else:
        return jsonify({"is_crisis": False, "crisis_level": "正常"})


@app.route('/initiate_crisis_response', methods=['POST'])
def initiate_crisis_response():
    # 由于没有具体的流程，接下来使用虚拟数据
    # data = request.get_json()
    # crisis_level = data.get('crisis_level')
    # user_info = data.get('user_info')
    crisis_level = "重度"
    user_info = {
        "user_name": "小红",
        "user_age": 25,
        "user_gender": "女"
    }

    if crisis_level and user_info:
        response_id = str(uuid.uuid4())
        crisis_responses[response_id] = {
            "crisis_level": crisis_level,
            "user_info": user_info,
            "status": "处理中"
        }
        return jsonify(crisis_responses[response_id])
    else:
        return jsonify({"errCode": "response_failed", "message": "未能成功启动相应的危机处理措施，请检查信息并重试。"}), 200


@app.route('/get_crisis_response_status', methods=['POST'])
def get_crisis_response_status():
    # 由于没有具体的流程，接下来使用虚拟数据
    # response_id = request.json.get('response_id')
    response_id = "response_001"
    if response_id in crisis_responses:
        status = crisis_responses[response_id]["status"]
        return jsonify({"status": status})
    else:
        return jsonify({"errCode": "invalid_id", "message": "提供的响应 ID 无效，无法查询处理状态。"}), 200


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5005)